#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

//初始化链表
ListNode* ListNode_init()
{
	ListNode* phead = (ListNode*)malloc(sizeof(ListNode));
	if (phead == NULL)
	{
		perror("ListNode_init::malloc");
		exit(-1);
	}
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

//尾插数据
void ListPushBack(ListNode* phead, ListDataType x)
{
	assert(phead);

	ListNode* tail = phead->prev;
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("ListPushBack::malloc");
		exit(-1);
	}
	newnode->prev = tail;
	newnode->val = x;
	newnode->next = phead;
	tail->next = newnode;
	phead->prev = newnode;
}

//从前往后打印数据
void ListNodePrintHead(ListNode* phead)
{
	if (phead == NULL)
	{
		printf("\n");
		return;
	}
	ListNode* cur = phead;
	//printf("%d ", cur->val);
	cur = cur->next;
	while (cur != phead)
	{
		printf("%d ", cur->val);
		cur = cur->next;
	}
	printf("\n");
}

//从后往前打印数据
void ListNodePrintBack(ListNode* phead)
{
	if (phead == NULL)
	{
		printf("\n");
		return;
	}
	ListNode* cur = phead->prev;
	while (cur != phead)
	{
		printf("%d ", cur->val);
		cur = cur->prev;
	}
	printf("\n");
}

void ListNodePopBack(ListNode* phead)
{
	//if (phead == NULL || (phead->next)== phead)//如果无数据则不做操作返回，温柔处理
	//{
	//	return;
	//}
	//暴力处理无数据删除操作
	assert(phead);
	assert(phead->next != phead);
	ListNode* tail = phead->prev;
	phead->prev = tail->prev;
	(tail->prev)->next = phead;
	//释放结点，防止内存泄露
	free(tail);
}

//删除节点
void LiseNodeErase(ListNode* pos)
{
	assert(pos != NULL);
	assert(pos->next != pos);
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
}

//查找结点并返回,找不到就返回空指针
ListNode* FindListNode(ListNode* phead, ListDataType x)
{
	if (phead->next == phead)
	{
		return NULL;
	}
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->val == x)
		{
			return cur;
		}
		else
		{
			cur = cur->next;
		}
	}
	return NULL;
}

//插入结点（地址前插）
void ListNodeInsert(ListNode* pos,ListDataType x)
{
	assert(pos != NULL);
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("ListNodeInsert::malloc");
		exit(-1);
	}
	ListNode* prev = pos->prev;
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
	newnode->val = x;
}